#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@NAME          : user_midd.py
@TIME          : 2025/02/27 15:23:00
@AUTHOR        : chenlip
@DESCRIPTION   : 权限控制中间件，用于验证用户权限，将在API接口或视图函数中使用
'''

from flask import request, jsonify
from flask_login import current_user
from functools import wraps

def admin_required(f):
    """要求用户是管理员才能访问的装饰器"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not current_user.is_authenticated or not current_user.is_admin:
            return jsonify({"success": False, "message": "需要管理员权限"}), 403
        return f(*args, **kwargs)
    return decorated_function

def api_login_required(f):
    """API接口用户认证装饰器(支持JWT或会话)"""
    @wraps(f)
    def decorated_function(*args, **kwargs):
        auth_header = request.headers.get('Authorization')
        
        # 检查是否已通过Flask-Login登录
        if current_user.is_authenticated:
            return f(*args, **kwargs)
            
        # 检查JWT头
        if auth_header and auth_header.startswith('Bearer '):
            from flask_jwt_extended import verify_jwt_in_request, get_jwt_identity
            try:
                verify_jwt_in_request()
                return f(*args, **kwargs)
            except:
                pass
                
        return jsonify({"success": False, "message": "需要登录"}), 401
    return decorated_function